'use strict'

const dbUtil = require('../util/dbUtil');
const mysqlUtil = require('../util/mysqlUtil');

/**
 * 查询
 */
let query = (req, res) => {
    let sql = `
		select l.*, u.name svn_author_name, (select count(1) from svn_log_path lp where lp.svn_revision = l.svn_revision) c
		from svn_log l left join svn_user u on u.code = l.svn_author
		where 1=1 
    `;

    let searchVal = mysqlUtil.paramFilter(req.body.searchVal);

    if (req.body.author != null && req.body.author != '') {
        sql += " and l.svn_author=" + mysqlUtil.escape(req.body.author);
    }
    if (req.body.date_range != null && req.body.date_range != '') {
        var dateStr = getDay(parseInt(req.body.date_range), '-');
        sql += " and l.svn_date like '" + dateStr + "%'";
    }
    if (searchVal != null && searchVal != '') {
        sql += " and (l.svn_message like '%" + searchVal + "%')";
    }

    sql += " order by l.svn_revision desc";

    dbUtil.partitionQuery(sql, req, res);
};

/**
 * 查询
 */
let querySvnPath = (req, res) => {
    let sql = `select * from svn_log_path lp where 1=1`;

    //let searchVal = mysqlUtil.paramFilter(req.body.searchVal);

    if (req.body.svn_revision != null && req.body.svn_revision != '') {
        sql += " and lp.svn_revision=" + req.body.svn_revision;
    }

    sql += " order by lp.svn_path asc";

    dbUtil.partitionQuery(sql, req, res);
};

function getDay(num, str) {
    var today = new Date();
    var nowTime = today.getTime();
    var ms = 24 * 3600 * 1000 * num;
    today.setTime(parseInt(nowTime + ms));
    var oYear = today.getFullYear();
    var oMoth = (today.getMonth() + 1).toString();
    if (oMoth.length <= 1) {
        oMoth = '0' + oMoth;
    }
    var oDay = today.getDate().toString();
    if (oDay.length <= 1) {
        oDay = '0' + oDay;
    }
    return oYear + str + oMoth + str + oDay;
}

exports.query = query;
exports.querySvnPath = querySvnPath;